package morning.cat.demo1.io2.file;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import org.junit.Test;

public class FileTest {

	@Test
	public void test1() throws IOException {
		File file = new File("E:\\javaio\\demo");
		if (!file.exists()) {
			System.out.println("mkdir");

			// 创建目录
			// file.mkdir();

			// 递归创建目录
			// file.mkdirs();

		} else {
			System.out.println("delete");
			file.delete();
		}

		System.out.println(file.isDirectory());
		System.out.println(file.isFile());

		// 常用的File对象的API
		System.out.println(file);
		System.out.println(file.toString());
		System.out.println(file.getAbsolutePath());

		System.out.println(file.getName());
		System.out.println(file.getParent());
		System.out.println(file.getParentFile().getAbsolutePath());
	}

	@Test
	public void test2() throws IOException {

		// File file2 = new File("e:\\javaio\\demo1.dat");
		File file2 = new File("e:\\javaio", "demo1.dat");
		if (!file2.exists()) {
			// 创建文件
			file2.createNewFile();
		} else {
			file2.delete();
		}

		System.out.println(file2.getName());
		System.out.println(file2.getParent());
	}

	@Test
	public void test3() throws IOException {
		File file = new File("E:\\javaio\\demo");
		if (file.isDirectory()) {
			String[] fileNames = file.list();
			for (String fileName : fileNames)
				System.out.println(file.getName() + "\\" + fileName);
		}
	}

	@Test
	public void test4() throws IOException {
		File file = new File("E:\\javaio\\demo");
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (File afile : files)
				System.out.println(afile.getName());
		}
	}

	@Test
	public void test5() throws IOException {
		File demo = new File("path1");
		if (!demo.exists()) {
			demo.mkdir();
		}

		File file = new File(demo, "raf.dat");
		if (!file.exists()) {
			file.createNewFile();
		}

		// 打开文件，进行随机读写
		RandomAccessFile raf = new RandomAccessFile(file, "rw");
		
		raf.write('A');
		raf.write('B');

		/* 序列化 */
		int i = 0x7ffffff;
		raf.write(i >>> 24);
		raf.write(i >>> 16);
		raf.write(i >>> 8);
		raf.write(i);

		// 指针的位置
		System.out.println(raf.getFilePointer());

		/* 反序列化 */

		// 读文件，把指针移到开头
		raf.seek(0);
		// int b = raf.read();
		// i = i | (b << 24);
		// b = raf.read();
		// i = i | (b << 16);
		// b = raf.read();
		// i = i | (b << 8);
		// b = raf.read();
		// i = i | b;
		// System.out.println(Integer.toHexString(i));

		byte[] buf = new byte[(int) raf.length()];
		raf.read(buf);

		System.out.println(Arrays.toString(buf));
		System.out.println(new String(buf));
		raf.close();
	}
}
